/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora.client.validation;

import com.google.gwt.json.client.JSONObject;
import redora.client.Persistable;
import redora.client.mvp.ClientFactory;
import redora.client.util.Field;
import redora.client.util.GWTViewUtil;

public class BusinessRuleViolation {
    public Class<? extends Persistable> cls;
    public Field field;
    public int ruleId;
    public String message;

    private BusinessRuleViolation(String className, String fieldName, int ruleId, String message, ClientFactory clientFactory) {
        this.cls = clientFactory.getLocator().locateClass(className);
        this.field = GWTViewUtil.from(fieldName, clientFactory.getLocator().locateFields(cls));
        this.ruleId = ruleId;
        this.message = message;
    }

    private BusinessRuleViolation(String className, String fieldName, String fieldClassName, int ruleId, String message, ClientFactory clientFactory) {
        this.cls = clientFactory.getLocator().locateClass(className);
        Class fieldCls;
        if (fieldClassName != null)
            fieldCls = clientFactory.getLocator().locateClass(fieldClassName);
        else
            fieldCls = cls;
        this.field = GWTViewUtil.from(fieldName, clientFactory.getLocator().locateFields(fieldCls));
        this.ruleId = ruleId;
        this.message = message;
    }

    public static BusinessRuleViolation from(JSONObject json, ClientFactory clientFactory) {
        String objectName = json.get("persistable").isString().stringValue();  //is mandatory
        int ruleId = Integer.parseInt(json.get("businessRuleId").toString()); //is mandatory
        return new BusinessRuleViolation(
                objectName
                , json.containsKey("field") ? json.get("field").isString().stringValue() : null
                , json.containsKey("fieldClass") ? json.get("fieldClass").isString().stringValue() : null
                , ruleId
                , clientFactory.getLocator().locateMessage().message(objectName, ruleId, json.containsKey("arguments") ? json.get("arguments").isArray() : null)
                , clientFactory
        );
    }

    public String toString() {
        return cls.getName() + (field == null ? "" : "." + field.name) + " " + ruleId;
    }
}
